const banner_img = document.querySelector('.banner_img')

// 存储导航索引与图片ID的映射关系
const navImageMap = new Map();
getBanner = () => {
    fetch('https://h5.youxiake.com/api/topic/web/h5/get/data?h5Id=12896&mark=https:%2F%2Fh5.youxiake.com%2Fhz%2F12896%3Fsource%3Dpinpai%26sdm%3D201.103.1.16')
        .then(res => res.json())
        .then(res1 => {
            // 计数器
            let count = 3;
            let Product_list = '';
            let liangdianTags = '';
            let ProductNew__item = '';
            let Product__tag = '';
            let plist__item = ''
            // 导航索引计数器（用于建立映射关系）
            let navIndex = 0;

            res1.data.infoBeanList.forEach((item, index) => {
                // 添加数据检查
                if (!item || !item.info) {
                    console.warn(`数据项 ${index} 缺少 info 属性:`, item);
                    return;
                }

                if (index < 2) {
                    // 前两张图片
                    banner_img.innerHTML += `<img src="${item.info[0]}">`;
                } else if (index == 2) {
                    banner_img.innerHTML += `
                        <video src="${item.info[0].qiniuSrc}"></video>
                        <div class="video_button" onclick="play_video()"></div>
                    `;
                } else if (index == 3) {
                    // 轮播图处理
                    let imglist = '';
                    // 检查 info 是否为数组
                    if (Array.isArray(item.info)) {
                        item.info.forEach(item1 => {
                            imglist += `<div class="swiper-slide"><img src="${item1.bg}"></div>`
                        })
                    }

                    // 添加轮播容器到DOM
                    banner_img.innerHTML += `
                        <div class="swiper-container">
                            <div class="swiper-wrapper">${imglist}</div>
                            <div class="swiper-pagination"></div>
                        </div>
                    `;

                    // 确保DOM已更新后再初始化Swiper
                    setTimeout(() => {
                        // 检查轮播容器是否存在
                        const swiperContainer = document.querySelector('.swiper-container');
                        if (!swiperContainer) {
                            console.error('轮播容器不存在');
                            return;
                        }

                        // 初始化Swiper - 适配v3版本的正确配置
                        var swiper = new Swiper(swiperContainer, {
                            pagination: '.swiper-pagination',
                            paginationClickable: true,
                            spaceBetween: 30,
                            centeredSlides: true,
                            autoplay: 2500,
                            autoplayDisableOnInteraction: false,
                            loop: true,
                            simulateTouch: true,
                            watchSlidesProgress: true,
                            watchSlidesVisibility: true
                        });

                        // 强制启动自动播放
                        swiper.startAutoplay();
                    }, 0);

                    // 设置轮播图样式
                    const swiperSlides = document.querySelectorAll('.swiper-slide');
                    const swiperImages = document.querySelectorAll('.swiper-slide img');

                    swiperSlides.forEach(slide => {
                        slide.style.width = '100%';
                        slide.style.height = '24.05rem';
                    });

                    swiperImages.forEach(img => {
                        img.style.width = '100%';
                        img.style.height = '100%';
                        img.style.objectFit = 'cover';
                    });
                } else {
                    // 其他数据处理
                    if (count % 2 !== 0 || index > 21) {
                        if (item.info && item.info[0]) {
                            // 锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位锚点定位
                            const imgId = `banner_img_${navIndex}`;
                            banner_img.innerHTML += `<img src="${item.info[0]}" id="${imgId}">`;
                            // 存储映射关系（从第三个导航项开始）
                            navImageMap.set(navIndex, imgId);
                            navIndex++;
                        }
                    } else {
                        ProductNew__item = '';
                        Product_list = '';
                        // 检查 info 是否为数组
                        if (Array.isArray(item.info)) {
                            item.info.forEach((item1, idx) => {
                                if (idx === 0 && item1.dailyPackageList && item1.dailyPackageList.length > 0) {
                                    liangdianTags = '';
                                    plist__item = ''
                                    if (Array.isArray(item1.liangdianTags)) {
                                        item1.liangdianTags.forEach(item2 => {
                                            liangdianTags += `<span class="tag">${item2}</span>`;
                                        });
                                    }

                                    if (Array.isArray(item1.dailyPackageList[0].batchList)) {
                                        item1.dailyPackageList[0].batchList.forEach((item2, index) => {
                                            plist__item += `
                                                <li>
                                                    <p class="h4">${item2.startDate}</p>
                                                    <p class="week">(${item2.startWeek})</p>
                                                    <p class="price">￥${item2.price}</p>
                                                    <p class="tip">${item2.statusLabel}</p>
                                                </li>
                                            `
                                        })
                                    }

                                    Product_list += `
                                    <div class="Product">
                                        <div class="img_box_thumb">
                                            <img class="thumb" src="${item1.image}" alt="">
                                        </div>
                                        <div class="Product__bottom">
                                            <div class="Product__type">
                                                <span class="trump">新品</span>
                                                ${item1.productName || ''}
                                            </div>
                                            <div class="Product__label">
                                                <div class="Product__label__tag">
                                                    <span>${item1.classTheme || ''}</span>
                                                    <span>${item1.classType || ''}</span>
                                                    <span class="daysd">${item1.days || ''}</span>
                                                </div>
                                                <div class="Product__label__right">${item1.sum || ''}</div>
                                            </div>
                                            <div class="Product__tag">${liangdianTags}</div>
                                            <div class="Product__package__list__box">
                                                <ul class="Product__package__list">
                                                   ${plist__item}
                                                </ul>
                                                <div class="Product__package__right">
                                                    <span>查</span><span>看</span><span>更</span><span>多</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                } else {
                                    Product__tag = '';
                                    if (Array.isArray(item1.liangdianTags)) { //判断是数组不能为空
                                        item1.liangdianTags.forEach((item2) => {
                                            Product__tag += `<span class="tag">${item2}</span>`;
                                        });
                                    }

                                    ProductNew__item += `
                                    <li>
                                        <div class="img_box_thumb">
                                            <img class="thumb" src="${item1.image || ''}" alt="">
                                        </div>
                                        <div class="Product__bottom">
                                            <div class="Product__type">${item1.productName || ''}</div>
                                            <div class="Product__label__tag">
                                                <span>${item1.classType || ''}</span>
                                                <span>${item1.classTheme || ''}</span>
                                                <span class="daysd">${item1.days || ''}</span>
                                            </div>
                                            <div class="Product__tag">${Product__tag}</div>
                                            <div class="Product__message">
                                                <div class="expense">￥${item1.price || 0}<b>起</b></div>
                                                <div class="right">${item1.sum || ''}</div>
                                            </div>
                                        </div>
                                    </li>
                                `;
                                }
                            });
                        }
                        banner_img.innerHTML += Product_list;
                        if (ProductNew__item) {
                            banner_img.innerHTML += `<ul class="ProductNew__item">${ProductNew__item}</ul>`;
                        }
                    }
                    count++;
                }
            });
        }).catch(err => {
            console.log('数据获取错误:', err);
        });
}
getBanner();

//播放视频
let bol = true;
function play_video() {
    // 更精确地选择视频按钮和对应的视频元素
    const video_button = document.querySelector('.video_button');
    // 选择与按钮同级的video元素，避免页面有多个视频时出错
    const video = video_button?.previousElementSibling;
    
    if (!video) {
        console.error('未找到对应的视频元素');
        return;
    }

    if (bol) {
        // 尝试播放视频
        video.play().then(() => {
            video_button.style.display = 'none';
        }).catch(error => {
            console.warn('播放失败:', error);
            alert('请点击视频开始播放');
            // 播放失败时重置状态
            bol = true;
        });
    } else {
        // 暂停视频
        video.pause();
        video_button.style.display = 'block';
    }

    // 确保状态正确切换
    bol = !bol;
}

const Nav__wrap = document.querySelector('.Nav__wrap')

// 将事件绑定逻辑封装为函数
function bindNavEvents() {
    const Nav__wrap_li = document.querySelectorAll('.Nav__wrap li')
    Nav__wrap_li.forEach((item, index) => {
        // 设置初始状态
        if (index === 0) {
            item.firstElementChild.style.display = 'block'
            item.style.color = '#000000'
        } else {
            item.firstElementChild.style.display = 'none'
            item.style.color = '#fff'
        }

        // 绑定点击事件
        item.onclick = function (event) {
            Nav__wrap_li.forEach((item1) => {
                item1.firstElementChild.style.display = 'none'
                item1.style.color = '#fff'
            })

            // 设置当前点击项的样式
            this.firstElementChild.style.display = 'block'
            this.style.color = '#000000'

            const targetImgId = navImageMap.get(index);
            const targetImg = document.getElementById(targetImgId);
            const targetTop = targetImg.getBoundingClientRect().top + window.pageYOffset;

            const offset = 44; // 你需要的具体像素值
            const scrollPosition = targetTop - offset;

            window.scrollTo({
                behavior: 'smooth',  // 平滑滚动
                top: scrollPosition,
            });

        }
    })
}


// 修改获取导航列表的函数
getNavList = () => {
    fetch('https://h5.youxiake.com/api/topic/web/h5/nav/title?h5Id=12896')
        .then(res => res.json())
        .then(res1 => {
            res1.data.navInfo.forEach(item => {
                Nav__wrap.innerHTML += `
                    <li id="${item.id}">
                        ${item.nav}
                        <i></i>
                    </li>
                `
            })
            // 数据加载完成后再绑定事件
            bindNavEvents()
        })
        .catch(err => {
            console.log(err)
        })
}
getNavList()




